package com.zqxq.lottery.api.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.newzqxq.common.utils.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect   //定义一个切面
@Configuration
@Slf4j
public class ControllerAspect {
    protected static Logger logger = LoggerFactory.getLogger(WebUtils.class);
    // 定义切点Pointcut controller下的所有包
    @Pointcut("execution(* com.zqxq.lottery.api.controller.*.*(..))")
    public void excudeService() {
    }

    @Around("excudeService()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        Object result = pjp.proceed();
        try {
            RequestAttributes ra = RequestContextHolder.getRequestAttributes();
            ServletRequestAttributes sra = (ServletRequestAttributes) ra;
            HttpServletRequest request = sra.getRequest();
            //打印日志
            WebUtils.logRequest(request);

            // result的值就是被拦截方法的返回值
            logger.info("请求结束，controller的返回值是 " + JSONObject.toJSONString(result));
        }catch (Exception e){
            e.printStackTrace();
            logger.info("controller 切面异常"+e.getMessage());
        }
        return result;
    }

}